//
//  HHLoginViewController.m
//  HHBroker
//
//  Created by Herui on 9/1/15.
//  Copyright © 2015 harry. All rights reserved.
//

#import "HHLoginViewController.h"
#import "JiaYuanEncrypt.h"
#import "HttpRequestManager.h"
#import "HHLoginWithPhoneNavi.h"
#import "HHSignInViewController.h"
#import "HHWelcomeViewController.h"



#define kTagOfTextField 1000
@interface HHLoginViewController () <UITextFieldDelegate, UINavigationControllerDelegate, HHLoginWithPhoneControllerDelegate>
@property (weak, nonatomic) IBOutlet UITextField *usernameTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;

@property (nonatomic, strong) UITableView *loginTable;
@property (nonatomic, copy) NSString *account;
@property (nonatomic, copy) NSString *password;

@end

@implementation HHLoginViewController{
    NSString *_uid;
    NSString *_token;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)dealloc
{

}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"登陆", nil);
        if (SYSTEM_IS_IOS7) {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
    }
    return self;
}

#pragma mark -
#pragma mark - Life Cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    NSArray *textFields = @[_usernameTextField, _passwordTextField];
    for (int i=0; i<textFields.count; i++) {
        UITextField *textField = [textFields objectAtIndex:i];
        textField.delegate = self;
        textField.tag = kTagOfTextField+i;
        [textField addTarget:self action:@selector(textFieldValueChanged:) forControlEvents:UIControlEventEditingChanged];
    }
    NSInteger info = [self getSavedAccount];
    [self performSelector:@selector(showKeyboardWithTag:) withObject:@(info) afterDelay:0.6];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationItem.backBarButtonItem = item;
    
}


#pragma mark -
#pragma mark -Function

- (void)showKeyboardWithTag:(NSNumber *)tag
{
    NSInteger info = [tag integerValue];
    if (info == 0) {
        [self.usernameTextField becomeFirstResponder];
    }
    if (info == 1) {
        [self.passwordTextField becomeFirstResponder];
    }
    
}

// 获取用户信息
- (void)getUserInfoReturn:(NSDictionary *)dicReturn
{
    NSDictionary *data = [dicReturn objectForKey:@"record"];
    if (data) {
        // uid token
        NSString *token = [dicReturn objectForKey:@"token"];
        NSString *uid = [data objectForKey:@"emp_id"];
        
        
        // 保存用户名和密码
        JiaYuanShareData *shareData = [JiaYuanShareData sharedInstance];
        //        if (![JiaYuanShareData setPassword:_password account:_account]) {
        //            return;
        //        }
        shareData.token = token;
        shareData.uid = uid;
        shareData.shopId = [data objectForKey:@"shop_id"];
        shareData.emp_rname = [data objectForKey:@"emp_rname"];
        shareData.emp_name = [data objectForKey:@"emp_name"];
        shareData.emp_city = [data objectForKey:@"emp_city"];
        shareData.address = [data objectForKey:@"address"];
        shareData.interviewStatus = [data objectForKey:@"interview_status"];
        shareData.idCard = [data objectForKey:@"emp_idcard"];
        NSString *bankCardNumber = [data objectForKey:@"payment_account"];
        if (bankCardNumber && ![bankCardNumber isKindOfClass:[NSNull class]]) {
            shareData.bankCardNumber = bankCardNumber;
        }
        // shopId
        NSString *shopId = [data objectForKey:@"shop_id"];
        if (!shopId || shopId.length == 0 || [shopId isEqual:@"0"]) {
            // 没有挂靠服务中心
            //            HHApplyServiceViewController *applyService = [[HHApplyServiceViewController alloc] init];
            //            applyService.title = @"登录成功";
            //            [self.navigationController pushViewController:applyService animated:YES];
            //            return;
            
        } else {
            // 登陆成功, 发出广播
            shareData.shopId = shopId;
            [self postLoginNotification];
            
        }
        
    }
}

- (void)postLoginNotification
{
    NSDictionary *signDic = @{KSignStatusKey:@(1)};
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationSign object:nil userInfo:signDic];
}

#pragma mark - 获取保存的帐号密码
/*
 *  @return 0 -- has none
 *          1 -- has account
 *          2 -- has both
 *
 */
- (NSUInteger)getSavedAccount
{
    NSUInteger countType = 0;
    //获取账户和密码
    self.account = [JiaYuanShareData currentAccount];
    self.password = [JiaYuanShareData passwordForCurrentAccount];
    if (self.account) {
        self.usernameTextField.text = self.account;
        countType ++;
    }
    if (self.password) {
        self.passwordTextField.text = self.password;
        countType ++;
    }
    if (_account == nil || _account.length == 0) {
        _account = @"";
    }
    if (_password == nil || _password.length == 0) {
        _password = @"";
    }
    return countType;
}


#pragma mark - Action
- (void)backBtn:(UIButton *)sender
{
    [self.view endEditing:YES];
    //cancel login send noticifation -1 is cancel login
    NSDictionary *useInfo = @{@"SignStatus":@(-1)};
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationSign
                                                        object:nil
                                                      userInfo:useInfo];
    [self dismissViewControllerAnimated:YES completion:nil];

}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:YES];

}


- (void)textFieldValueChanged:(UITextField *)textField
{
    
    if (textField.tag == kTagOfTextField) {
        self.account = textField.text;
    } else {
        self.password = textField.text;
    }
}

//Login
- (IBAction)startLogin
{
    [self.view endEditing:YES];
    // 检测输入的有效性
    self.account = self.usernameTextField.text;
    self.password = self.passwordTextField.text;
    
    NSString *user = [_account stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if ([user isEqualToString:@""]) {
        MBProgressHUD *hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hub.mode = MBProgressHUDModeText;
        hub.labelText = NSLocalizedString(@"请输入手机号/用户名", @"");
        [hub hide:YES afterDelay:1];
        return;
    }
    
    if ([_password isEqualToString:@""]) {
        MBProgressHUD *hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hub.mode = MBProgressHUDModeText;
        hub.labelText = NSLocalizedString(@"请输入密码", @"");
        [hub hide:YES afterDelay:1];
        return;
    }
    
    DLog(@"the account : %@, the pass : %@", self.account, self.password);
    [self doSignin:user withPassWord:_password realLogin:YES];



}
- (IBAction)startSignin
{
    HHSignInViewController *signin = [[HHSignInViewController alloc] init];
    [self.navigationController pushViewController:signin animated:YES];

}

//forget password
- (IBAction)forgetPasswordButtonClicked:(UIButton *)sender
{
    HHLoginWithPhoneNavi *loginWithPhone = [[HHLoginWithPhoneNavi alloc] init];
    loginWithPhone.delegate = self;
    [self presentViewController:loginWithPhone animated:YES completion:nil];

}

#pragma mark - Event
- (IBAction)loginButtonClick:(UIButton *)sender
{
    NSString *theUser = self.usernameTextField.text;
    NSString *thePass = self.passwordTextField.text;
    thePass = [JiaYuanEncrypt AES128Encrypt:thePass key:kSecuCode];
    NSString *urlString = [NSString stringWithFormat:@"%@?username=%@&password=%@", kUrlLogin, theUser, thePass];
    [HttpRequestManager getWithUrlString:urlString success:^(id response) {
        NSInteger code = [[response objectForKey:@"code"] integerValue];
        DLog(@"succ");
        if (code == 1) {
           
            [self getUserInfoReturn:response];
            
            
        } else {
            
        }
    } failure:^(NSError *error) {
        DLog(@"failure");
    } isLogin:NO];
}

#pragma mark - Http(向服务器请求登陆)
// 内部登陆
-(void)doSignin:(NSString*)theUser withPassWord:(NSString*)thePass realLogin:(BOOL)isRealLogin
{
    MBProgressHUD *hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hub.labelText = @"正在提交";
    thePass = [JiaYuanEncrypt AES128Encrypt:thePass key:kSecuCode];
    NSString *urlString = [NSString stringWithFormat:@"%@?username=%@&password=%@", kUrlLogin, theUser, thePass];
    hub.mode = MBProgressHUDModeIndeterminate;
    [HttpRequestManager getWithUrlString:urlString success:^(id response) {
        NSInteger code = [[response objectForKey:@"code"] integerValue];
        if (code == 1) {
            hub.mode = MBProgressHUDModeText;
            hub.labelText = @"登录成功";
            hub.completionBlock = ^ {
                [self getUserInfoReturn:response];
            };
            [hub hide:YES afterDelay:1];
            
            
        } else {
            [hub hide:NO];
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"账号或密码错误，请重新填写" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
            
        }
    } failure:^(NSError *error) {
        hub.labelText = @"网络有点问题!";
        [hub hide:YES afterDelay:1];
    } isLogin:NO];
}
#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == _usernameTextField) {
        self.account = textField.text;
        [_passwordTextField becomeFirstResponder];
    } else if (textField == _passwordTextField){
        self.password = textField.text;
        [self startLogin];
    }
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    return YES;
}

#pragma mark - HHLoginWithPhoneControllerDelegate
- (void)loginWithPhoneViewController:(HHLoginWithPhoneNavi *)controller didFinishLoginWithResponse:(NSDictionary *)response
{
    [controller dismissViewControllerAnimated:YES completion:^{
        [self getUserInfoReturn:response];
    }];

}

- (void)loginWithPhoneViewController:(HHLoginWithPhoneNavi *)controller didCancelWithResult:(LoginCancelResult *)result
{
    BOOL animate = result == LoginCancelBySignedPhone ? NO : YES;
    [controller dismissViewControllerAnimated:animate completion:^{
        if (result == LoginCancelBySignedPhone) {
            HHWelcomeViewController *welcome = (HHWelcomeViewController *)self.navigationController.viewControllers[0];
            welcome.nextToGo = JYADRegister;
            [self.navigationController popViewControllerAnimated:YES];
        } else {
        
        }
    
    }];

}

@end
